<template>
    <div class="custom-search-form-container" ref="formContainer">
        <a-form :ref="(ref: FormInstance | any) => initFormRef(ref)" :model="formState" :label-col="labelCol"
            :wrapper-col="wrapperCol" class="adaptive-search-form">
            <a-row :gutter="[16, 16]" align="middle">
                <template v-for="(item, index) in visibleItems" :key="index">
                    <a-col v-if="!item.hidden && (isExpanded || index < visibleCount)" :xxl="item.xxl || 6"
                        :xl="item.xl || 8" :lg="item.lg || 8" :md="item.md || 12" :sm="item.sm || 24" :xs="24">
                        <a-form-item :label="item.label" :name="item.name">
                            <!-- 输入框 -->
                            <a-input class="custom-input" v-if="item.type === 'input'"
                                v-model:value="formState[item.name]"
                                :placeholder="item.placeholder || `请输入${item.label}`"
                                :allow-clear="item.allowClear ?? false" />

                            <!-- 下拉选择 -->
                            <MASelect v-else-if="item.type === 'select'" v-model:value="formState[item.name]"
                                :placeholder="item.placeholder || `请选择${item.label}`" :options="item.options"
                                :mode="item.mode" @change="(val, row) => item.onChange?.(val, row)"
                                :styles="{ width: '99%' }" />
                            <!-- treeselect -->
                            <a-tree-select v-else-if="item.type === 'treeSelect'" :styles="{ width: '99%' }"
                                v-model:value="formState[item.name]" :field-names="item?.props?.fieldNames" show-search
                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto', ...item?.dropdownStyle }"
                                :placeholder="item.placeholder || `请选择${item.label}`" allow-clear
                                tree-default-expand-all :filterTreeNode="item?.filterTreeOption || filterTreeOption"
                                :treeData="item?.treeData"
                                @select="(value, node) => item.onSelect?.(value, node)"
                                @change="(val, row) => item.onChange?.(val, row)" />

                            <!-- 日期选择 -->
                            <a-date-picker v-else-if="item.type === 'date'" v-model:value="formState[item.name]"
                                :placeholder="item.placeholder || `请选择${item.label}`"
                                :value-format="item.valueFormat || 'YYYY-MM-DD'" :format="item.format || 'YYYY-MM-DD'"
                                style="width: 100%" />

                            <!-- 日期范围选择 -->
                            <a-range-picker v-else-if="item.type === 'range'" v-model:value="formState[item.name]"
                                :placeholder="item.placeholder || ['开始日期', '结束日期']"
                                :value-format="item.valueFormat || 'YYYY-MM-DD'" :format="item.format || 'YYYY-MM-DD'"
                                :show-time="item.showTime || false" style="width: 100%" />

                            <!-- 自定义插槽 -->
                            <slot v-else-if="item.type === 'slot'" :name="item.slotName || item.name" :item="item"
                                :formState="formState" />
                        </a-form-item>
                    </a-col>
                </template>
            </a-row>
        </a-form>
        <div class="form-actions-container" :style="{ paddingTop: visibleItems.length > maxLength ? '0' : '16px' }">
            <a-button v-if="visibleItems.length > maxLength" type="link" @click="toggleExpand" class="toggle-btn">
                <span> {{ isExpanded ? '收起' : '展开' }}</span>
                <template #icon>
                    <UpOutlined v-if="isExpanded" />
                    <DownOutlined v-else />
                </template>
            </a-button>
            <a-button v-auth="auth" type="primary" @click="handleSearch" class="search-btn">
                <template #icon>
                    <SearchOutlined />
                </template>
                搜索
            </a-button>
            <a-button v-auth="auth" @click="handleReset" class="reset-btn">
                <template #icon>
                    <RedoOutlined />
                </template>
                重置
            </a-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick, computed, onMounted, onUnmounted, watch } from 'vue';
import { SearchOutlined, RedoOutlined, DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import { debounce } from 'lodash-es'
import { useSearchForm } from './hooks/hooks'
import { FormInstance } from 'ant-design-vue';
import mitter from '@/utils/bus'
import { storage } from '@/storage'

const props = defineProps({
    // 表单配置项
    items: {
        type: Array as any,
        required: true,
        default: () => [],
    },
    // 标签布局
    labelCol: {
        type: Object,
        default: () => ({ style: { width: "110px" } }),
    },
    // 控件布局
    wrapperCol: {
        type: Object,
        default: () => ({ span: 16 }),
    },
    // 初始表单值
    initialValues: {
        type: Object,
        default: () => ({}),
    },
    auth: {
        type: String
    },
    maxLength: {
        type: Number,
        default: 4
    }
});

const { initFormRef, visibleItems, formState, resetForm, clearFields, getFormInstance, getField } = useSearchForm(props)

const emit = defineEmits(['search', 'reset', 'sumHeight']);
const windowWidth = ref(window.innerWidth);
const showActionsInline = ref(true);
const isExpanded = ref(true);
// 添加高度计算逻辑
const formContainer = ref();

const calculateHeight = debounce(() => {
    nextTick(() => {
        if (!formContainer.value) return;
        const clientHeight = formContainer.value?.clientHeight;
        storage.local.set('actionHeight', clientHeight + '')
        emit('sumHeight', formContainer.value?.clientHeight);
        mitter.emit('resetHeight', clientHeight);
    })

}, 10);

watch(() => isExpanded.value, () => {
    calculateHeight()
});


// 计算一行显示的表单项数量
const visibleCount = computed(() => {
    if (windowWidth.value < 768) { // 移动端
        return 1;
    } else if (windowWidth.value < 992) { // 平板
        return 2;
    } else if (windowWidth.value < 1600) { // 小桌面
        return 3;
    } else { // 大桌面
        return 4;
    }
});

// 切换展开收起状态
const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
};

// 计算是否应该内联显示操作按钮
const calculateActionsPosition = () => {
    const visibleCountValue = visibleCount.value;
    showActionsInline.value = (visibleItems.value.length <= visibleCountValue) || isExpanded.value;
};

// 处理窗口大小变化
const handleResize = () => {
    windowWidth.value = window.innerWidth;
    calculateActionsPosition();
    calculateHeight();
};

onMounted(() => {
    window.addEventListener('resize', handleResize);
    calculateActionsPosition();
    calculateHeight()
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    storage.local.remove('actionHeight')
});

// 搜索方法
const handleSearch = debounce(() => {
    emit('search', formState);
}, 300);

// 重置方法
const handleReset = debounce(() => {
    resetForm();
    emit('reset', formState);
}, 500);

const clearField = (name, valu) => {
    clearFields(name, valu)
}

function filterTreeOption(input: string, treeNode: any): boolean {
    return treeNode.name.includes(input)
}

// 暴露方法给父组件
defineExpose({
    formState,
    reset: () => handleReset(),
    search: () => handleSearch(),
    clearField,
    getFormInstance,
    getField
});
</script>

<style scoped>
.custom-search-form-container {
    width: 100%;
    display: flex;
    justify-content: space-between;
}

/* 使用深度选择器 */
:deep(.custom-input input::placeholder) {
    color: #7f7f7f;
}

.adaptive-search-form {
    flex: 1;
    padding-left: 10px;
    padding-right: 10px;
    padding-bottom: 10px;
    padding-top: 16px;
    background: #fff;
    border-radius: 2px;
    /* margin-bottom: 8; */
}

.action-buttons {
    display: flex;
    align-items: center;
    padding-top: 4px;
}

.action-buttons-row {
    margin-top: 8px;
    justify-content: flex-end;
}

.form-actions-container {
    /* padding-top: 16px; */

    .search-btn {
        margin-right: 12px;
    }

    .reset-btn {
        margin-right: 0;
    }
}

.toggle-btn {
    margin-right: 12px;
    margin-top: 16px;
}

:deep(.ant-form-item) {
    margin-bottom: 0;
}
</style>
